package com.accgm.api.resources.user;

import java.util.HashMap;

import net.sf.json.JSONObject;

import org.restlet.Request;

import com.accgm.api.db.dao.AccgmUserDao;
import com.accgm.api.db.model.AccgmUserModel;
import com.accgm.api.resources.base.BaseResource;
import com.accgm.api.utils.ACCGMJSONUtils;
import com.accgm.api.utils.ACCGMToken;
import com.accgm.api.utils.Encryptstr;
import com.accgm.api.utils.JSONFromBean;

public class LoginResource extends BaseResource {

	AccgmUserDao accgmUserDao = AccgmUserDao.getInstance();
	@Override
	protected void initParams(Request request) {
		isAuth = false;
	}

	@Override
	protected JSONObject getMethod(JSONObject json) {
		String username = getParameter("account","");//账号
		String password = getParameter("password","");//密码
		AccgmUserModel accgmUser = accgmUserDao.findByUsername(username);
		if(accgmUser == null){
			return failRequest("找不到该账号",json);
		}
		System.out.println(Encryptstr.decode(accgmUser.getPassword()));
		if(!Encryptstr.decode(accgmUser.getPassword()).equals(password)){
			return failRequest("密码错误",json);
		}
		HashMap<String,Object> dataMap = new HashMap<String,Object>();
		dataMap.put("access_token", ACCGMToken.encodeToken(accgmUser.getId(), ""));
		HashMap<String,Object> userMap = new HashMap<String,Object>();
		userMap.put("add_time", accgmUser.getAddTime().toString());
		userMap.put("update_time", accgmUser.getUpdateTime().toString());
		userMap.put("birthday", accgmUser.getBirthday());
		userMap.put("username", accgmUser.getName());
		userMap.put("sex", accgmUser.getSex());
		userMap.put("height", accgmUser.getHeight());
		userMap.put("medical", accgmUser.getCheckMessage());
		userMap.put("ear_lobe", accgmUser.getEarlobeWidth());
		userMap.put("ear_hole", accgmUser.getIsEarPiercing());
		userMap.put("account", accgmUser.getUsername());
		userMap.put("weight", accgmUser.getWeight());
		JSONObject jsonObject = JSONObject.fromObject(userMap);
		dataMap.put("user", jsonObject);
		json.put("data", dataMap);
		return succRequest("登录成功",json);
	}

	@Override
	protected JSONObject postMethod(JSONObject json) {
		return this.getMethod(json);
	}

}
